package com.yyge.config;

import cn.hutool.json.JSONUtil;
import com.yyge.controller.admin.product.dto.DishFlavorItem;
import com.yyge.controller.admin.product.dto.DishFlavorProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author gityyge
 * @Description 口味列表默认的配置
 * @Date 2023/7/13 15:00
 * @Version 1.0
 */
@Configuration
public class DishFlavorConfig {
    public static final String DISHFLAVOR_KEY="dish_flavor";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 初始化数据到Redis中
     */

    @PostConstruct
    public void initConfig(){
        //分布式锁
        Boolean aBoolean=this.redisTemplate.opsForValue().setIfAbsent("lock_dish_flavor","初始化",1, TimeUnit.DAYS);

        //加锁成功
        if(aBoolean){
            System.out.println("----- 初始化 口味到redis中 ------");
            List<DishFlavorProperty> dishFlavorPropertyList=this.dishFlavorData();
            for (int i = 0; i < dishFlavorPropertyList.size(); i++) {
                String field="item"+i;
                this.redisTemplate.opsForHash().put(DISHFLAVOR_KEY,field,dishFlavorPropertyList.get(i));
            }
        }
    }

    private List<DishFlavorProperty> dishFlavorData(){
        List<DishFlavorProperty> arr=new ArrayList<>();

        String[] name={"温度","甜度","辣度"};
        String[] values={
                "[\"正常冰\",\"少冰\",\"常温\",\"温热\"]",
                "[\"正常糖\",\"七分糖\",\"五分糖\"]",
                "[\"不辣\",\"微辣\",\"中辣\",\"麻辣\"]"
        };

        for (int i = 0; i < name.length; i++) {
            DishFlavorProperty vo=new DishFlavorProperty();
            vo.setName(name[i]);

            //组装值
            List<DishFlavorItem> arrProp=new ArrayList<>();
            //得到默认的值 转换成Json
            List<String> stringList= JSONUtil.toList(values[i],String.class);

            for (String s : stringList) {
                DishFlavorItem item=new DishFlavorItem();
                item.setValue(s);
                item.setPrice(0);
                arrProp.add(item);
            }

            vo.setValue(arrProp);
            arr.add(vo);
        }
        return arr;
    }
}
